package com.blockchain.controller;


import com.blockchain.model.User;
import com.blockchain.repository.UserRepository;
import com.blockchain.service.UserService;
import com.blockchain.service.dto.LoginRequestDTO;
import com.blockchain.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@CrossOrigin(origins = "http://localhost:8080")
@RestController
public class LoginController {

    private UserService userService;
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    public LoginController(UserService userService,JwtTokenUtil jwtTokenUtil){
        this.jwtTokenUtil=jwtTokenUtil;
        this.userService=userService;
    }
    @Autowired
    private UserRepository userRepository;
    @PostMapping("/login")
    public ResponseEntity<String> loginUser(@RequestBody LoginRequestDTO loginRequestDTO){


        //获取登陆类型
        String loginType=loginRequestDTO.getLoginType();
        if("username_password".equals(loginType)){
            userService.loginWithUsernameAndPasswordUser(loginRequestDTO);
            User user=userRepository.findByUsername(loginRequestDTO.getUsername());
            //生成令牌
            String token=jwtTokenUtil.generateToken(user.getUserId());
            return ResponseEntity.ok(token);
        }else if("email_captcha".equals(loginType)){
            userService.loginWithEmailUser(loginRequestDTO);
            User user=userRepository.findByEmail(loginRequestDTO.getEmail());
            String token=jwtTokenUtil.generateToken(user.getUserId());
            return ResponseEntity.ok(token);
        }else {
            return ResponseEntity.badRequest().body("不支持的登陆类型");
        }

    }
}
